import {
    Layer, Map, Point
} from "../../modules/CloudMap/src/Cloud";
import {
    CFeature,
    CPoint,
    CStyle,
    CFill,
    CIcon,
    CStroke,
    CText,
    CVectorLayer,
    CVector,
    CLineString,
    CunByKey,
    CasColorLike,
    CasArray,
    DEVICE_PIXEL_RATIO,
    CPolygon
} from "../../modules/CloudMap/src/modules/ol";
import { message } from "antd";
import PathRequest from "../../services/pathPlan";
import { Component } from "react";

const scss = require('../../assets/styles/map.module.scss');

let pointList: any = [];
let click: any;
let polygonLayer: any = [];
const CLOUD = (window as any)['env'];
export default class PathPlan extends Component {
    layer: any;
    maps: any;
    state = {
        clickIs_: false
    }
    componentDidMount() {
        this.initMap()
    }
    /**
     * 初始化地图
     */
    initMap = () => {
        // Initialize the cloud map
        this.layer = new Layer();
        // Creating a map object
        this.maps = new Map({ id: 'map', zoom: 10 });
        let params = {
            Zoom: [[], []],
            zIndex: [3],
            url: [CLOUD.wms_luwang],
            service: "WMS",
            version: " 1.1.1",
            request: "GetMap",
            format: "image/png",
            transparent: true,
            layers: ["test:navigation"],
            exceptions: "application/vnd.ogc.se_inimage"

        };
        let roadNet = this.layer.TileCWMS({ Source: params });
        this.maps.addLayer(roadNet[0]);
        this.drawLine()
    }
    /**
     * 选点完之后发起请求获取路径
     * @param map 
     */
    pathPlanning = () => {
        PathRequest.PathPlan(
            {
                start: {
                    x: pointList[0].x,
                    y: pointList[0].y
                },
                end: {
                    x: pointList[1].x,
                    y: pointList[1].y
                }
            },
            (res) => {
                let list: any = [];
                res.data.data.forEach((item: any) => {

                    list.push([item.x, item.y]);
                    console.log([item.x, item.y]);

                });

                this.Draw(list)
            }
        );
    }

    /**
     * 开始选点
     * @param map 
     * @param clickIs_ 
     */
    clickOn = (clickIs_: any) => {
        if (clickIs_) {
            message.info(`开始选点`);
            message.config({
                top: 100,
            })
            click = this.maps.on('click', (evt: any) => {
                var pixel = this.maps.getEventPixel(evt.originalEvent);//获取点击的像素点
                var coordinate = this.maps.getCoordinateFromPixel(pixel);//获取像素点的坐标
                pointList.push({
                    x: coordinate[0],
                    y: coordinate[1]
                });
                message.info(`已选${pointList.length}个点`);
                message.config({
                    top: 100,
                })
                if (pointList.length === 2) {
                    this.pathPlanning();

                }
            });

        }
        else {
            CunByKey(click);
            polygonLayer.forEach((item: any) => {
                this.maps.removeLayer(item);
            })

            message.info(`取消监听`);
            message.config({
                top: 100,
            })
        };
    }
    /**
     * 测试绘制线段
     */
    drawLine = () => {
        this.maps.once('postrender', () => {
            let list: any = [
                [119.70301748908899, 28.539117929593238], [119.89331748908899, 28.519117929593238], [119.89331748908899, 28.819117929593238]
            ];
            let iconStart = new CFeature({
                geometry: new CPoint(list.slice(0)[0], "XY"),

            });
            let iconEnd = new CFeature({
                geometry: new CPoint(list.slice(-1)[0], "XY"),

            });
            iconStart.setStyle(new CStyle({
                image: new CIcon({
                    opacity: 1,
                    scale: 0.1,
                    src: require('../../assets/icon/start.png').default,
                })
            }));
            iconEnd.setStyle(new CStyle({
                image: new CIcon({
                    opacity: 1,
                    scale: 0.15,
                    // size:600,
                    offset: [0, 0],
                    src: require('../../assets/icon/end.png').default,
                })
            }));


            let polygonFeature = new CFeature({
                geometry: new CLineString(list)
                // geometry: new CPolygon([list])
            });

            var canvas: any = document.createElement('canvas');
            var context: any = canvas.getContext('2d');
            // var canvas1: any = document.createElement('canvas');
            var context1: any = canvas.getContext('2d');
            var speed = 0;
            var startPoint = 0;
            setInterval(() => {
                let wi = 80;

                canvas.width = wi;
                canvas.height = 50;

                // canvas1.width = wi;
                // canvas1.height = 5;
                if (Math.abs(startPoint) > canvas.width) {
                    startPoint = -5
                }
                context.fillStyle = 'rgba(0,0,0,0.1)';//这里颜色要与背景图的颜色一样，但是透明度要小
                context.rect(0, 0, 800, 600);//整个绘制区域的大小

                speed = -2;
                startPoint += speed;
                let gradient = context.createLinearGradient(0, 0, canvas.width + 5, 0);
                gradient.addColorStop(0, 'blue');
                gradient.addColorStop(1, '#94929200');
                // white background

                context.fillStyle = gradient;

                context.fillRect(startPoint, 0, canvas.width, canvas.height);

                // context.fillStyle = "red";
                context.fillRect(startPoint + canvas.width + 5, 0, canvas.width, canvas.height);





                var pattern = (() => {
                    return context.createPattern(canvas, 'repeat');
                })();

                polygonFeature.setStyle(new CStyle({
                    fill: new CFill({
                        // color: pattern
                        color: '#1fca04'
                    }),
                    stroke: new CStroke({
                        color: pattern,
                        width: 5,
                    }),

                }))

            }, 50);

            polygonLayer.push(new CVectorLayer({
                zIndex: 8,
                source: new CVector({
                    features: [polygonFeature]
                })
            }))
            this.maps.addLayer(polygonLayer.slice(-1)[0])
            pointList = [];
        });

        var canvas1: any = document.getElementById('canvas');
        var context1 = canvas1.getContext('2d');
        canvas1.width = 80;
        canvas1.height = 100;
        var circle = {                         //创建一个圆形对象
            x: 250,
            y: 250,
            radius: 50,
            direction: 'right',

            move: function () {
                if (this.direction === 'right') {
                    if (this.x <= 440) {
                        this.x += 5;
                    }
                    else {
                        this.direction = 'left';
                    }
                } else {
                    if (this.x >= 60) {
                        this.x -= 5;
                    }
                    else {
                        this.direction = 'right';
                    }
                }
            },

            draw: function () {
                context1.beginPath();
                context1.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, true);
                context1.closePath();
                context1.fillStyle = 'blue';
                context1.fill();
            }
        };

        function animation() {
            circle.move();    //更新
            context1.clearRect(0, 0, canvas1.width, canvas1.height);  //清除
            circle.draw();   //绘制
            requestAnimationFrame(animation);  //循环
        }
        circle.draw();
        animation();

    }
    /**
     * 画板，开始画线
     * @param map 
     * @param list 
     */
    Draw = (list: any) => {
        let iconStart = new CFeature({
            geometry: new CPoint(list.slice(0)[0], "XY"),

        });
        let iconEnd = new CFeature({
            geometry: new CPoint(list.slice(-1)[0], "XY"),

        });
        iconStart.setStyle(new CStyle({
            image: new CIcon({
                opacity: 1,
                scale: 0.1,
                src: require('../../assets/icon/start.png').default,
            })
        }));
        iconEnd.setStyle(new CStyle({
            image: new CIcon({
                opacity: 1,
                scale: 0.15,
                // size:600,
                offset: [0, 0],
                src: require('../../assets/icon/end.png').default,
            })
        }));


        let polygonFeature = new CFeature({
            geometry: new CLineString(list)
        })
        polygonFeature.setStyle(new CStyle({
            fill: new CFill({
                color: 'rgba(255, 255, 255, 0.8)',
            }),
            stroke: new CStroke({
                color: (Math.random() * 10 > 7) ?
                    'rgb(19, 225, 255)' :
                    (Math.random() * 10 < 4 ? 'rgb(0, 123, 250)' : 'rgb(255, 217, 0)'),
                width: 6,
            }),
            text: new CText({
                text: ''
            })
        }))


        polygonLayer.push(new CVectorLayer({
            zIndex: 8,
            source: new CVector({
                features: [polygonFeature, iconStart, iconEnd]
            })
        }))
        this.maps.addLayer(polygonLayer.slice(-1)[0])
        pointList = [];

    }

    render() {
        return (
            <div>
                <div
                    id={'map'}
                    className={scss['map']}
                ></div>
                <div className={scss['path-plan']}>
                    <span onClick={() => { this.clickOn(true) }}>开 始</span>
                    <span onClick={() => { this.clickOn(false) }}>取 消</span>
                </div>
                <canvas id="canvas"></canvas>

            </div>
        )
    }
}